var stageOper;// 可操作场景的对象
var container;
var initConfig;
var initjson;
var jyztEchartOption;
var currentModule;//当前右键选中的组件
var currentModule_shape;//当前右键选中的组件元素
var switchIconUrl = "";//开关选择后的图标路径
var imageStatusUrl = "";//状态图片路径
var imageBackgroundUrl="";//画面背景图片
var hardware_id="";//当前选择的硬件传感器数据点的id
var hardware_Text="";//当前选择的硬件传感器数据点的描述
var selectOneWhere="";//选择数据点时，第一个下拉框的条件
var userId = ""; //用于查询我的组件
//右键菜单节点
var menuNode;

var colorpicker;
var slider;
var tree;
var table;
var form;

var stage_id;         //场景画面id
var stageModule_id;  //模板id
var stageModuleName=""; //模板名称
var isCancel=1;  //1 调用模板保存，0 不调用
var targetStage="";//跳转的目标画面 格式  画面id-画面名称  df45524566323-简单画面

var basicStateConfig={};//基础信息状态配置
var transformerArrayTemp=new Array();//临时讲复制后的组件放在这里，后面会讲里面的组件放到编辑框。
var transformerLength=0;//框框框选的个数
var stackZ = new ArrayStack();
var stackY = new ArrayStack();
var lastkeyCode = -1;
var spaceIsDown = false;// 空格键是否按下 默认没有按下  现在的含义是是否按下 Alt键

var conditionConfig={};//条件弹框配置
// var layer=null;
// var index = null;
// layui.use(['layer'], function(){
// 	layer = layui.layer;  //this.layer
// 	indexLoad = layer.load(2, {time: 20*1000});
// })
$(function(){
    "use strict";
     stage_id= $_GET.stageId;
     selectOneWhere = $_GET.selectOneWhere;
     userId = $_GET.userId;
   // deadlineForValidation();时间验证暂时无用
    menuNode = document.getElementById('menu');
    //初始化表单面板灯html常见元素
    layui.use(['element','form','colorpicker','slider','tree','table'], function(){
         table = layui.table;
         form = layui.form;
        var element = layui.element;
         colorpicker = layui.colorpicker;
         slider = layui.slider;
         tree = layui.tree;




        //监听辅助线按钮
        form.on('checkbox(hbfzx)', function(data){
            stageOper.setStageGrid(data.elem.checked);
            if(!data.elem.checked){
                $("#gridColorGroup").hide();
                $('#gridColor').val("");
            }else{
                $("#gridColorGroup").show();
            }
        });
        //监听场景是否移动单选按钮
        form.on('radio(stagedrag)', function(data){
            stageOper.setStageDrag(eval(data.value));
        });

        //监听右边tab切换
        element.on('tab(zt_attr_tab)', function(data){
            if(data.index==2){
                var stageJson = stageOper.stage.toJSON();
                var layerChildren =  stageOper.layer.getChildren();
               // $("#stageStructureTitle").text("画布图层"+layerChildren.length);
                $("#stageStructure").text("画面元素共"+layerChildren.length+"个;该标签页暂未规划功能");

                /* 这颗树的渲染比较慢很好资源，目前也没有什么用，先注释。
                stageJson =  stageJson.replace(/className/g,'spread":"true","title');
                tree.reload('stageStructure',{
                    data:   eval('(['+stageJson+'])')
                });*/
            }
        });

       //画图结构图层 树 暂时去掉，没有什么实际作用
       /* tree.render({
            elem: '#stageStructure' //默认是点击节点可进行收缩
            ,id: 'stageStructure'
            ,data: ""
            ,onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
            ,click: function(obj){
                  layer.msg(obj.data.attrs.id);
               }
        });*/

// ------------------------------------------------------------------------------------------------------------------------
         jyztEchartOption = new EchartOption();//echart组件配置
         initConfig = new InitConfig();
        //读取配置文件
        $.ajaxSettings.async = false; //设置getJson同步
        $.getJSON("config/init.json", function (data){
            initjson=data;
        });

        $.ajaxSettings.async = true;//设置getJson异步

        stageOper = new StageOperation();
        stageOper.initStage(stage_id,element);//初始化大小是1024*768

		//初始化左侧组件面板（基础组件）
        var module_base = eval("initConfig."+initjson.initBaseMoudleFunction+"()");
        stageOper.setLeftModulePanel(module_base);
		//初始化左侧组件面板（图纸组件）
		var module_draw = eval("initConfig." + initjson.initDrawsMoudleFunction + "()");
		stageOper.setLeftDrawsModulePanel(module_draw);
		//2023年3月10日，交换了上面两者加载顺序
        //初始化左侧组件面板（图库组件）
        var module_image = eval("initConfig."+initjson.initMapStorageMoudleFunction+"()");
        stageOper.setLeftMapStorageModulePanel(module_image);
       // layer.close(indexLoad);

        //初始化左侧组画面装饰（画面装饰）
        var module_decoration = eval("initConfig."+initjson.initMyDecorationMoudleFunction+"()");
        stageOper.setLeftModuleDecorationPanel(module_decoration);

        //初始化左侧组（画面模板）
       // var module_stage = eval("initConfig."+initjson.initMyMoudleStageFunction+"()");
       // stageOper.setLeftModulestagePanel(module_stage);

        //初始化左侧组件面板（我的组件）
        var module_my = eval("initConfig."+initjson.initMyMoudleFunction+"()");
        stageOper.setLeftMyModulePanel(module_my);
        //初始化左侧组件面板 画面模板--我的模板
        //var moduleStageJson_my = eval("initConfig."+initjson.initMyMoudleStageJsonFunction+"(UrlParam)");
        //stageOper.setLeftMyModuleStageJsonPanel(moduleStageJson_my);





        //左侧面板组件拖拽结束后的监听 start----------------------------------
        container = stageOper.stage.container();
        container.addEventListener('dragover', function (e) {
            e.preventDefault();
        });

        container.addEventListener('drop', function (e) {
            e.preventDefault();
            var moduleJsonObjId = e.dataTransfer.getData("text");
            stageOper.stage._setPointerPosition(e);
            var modulePoint=stageOper.stage.getPointerPosition();
            var moduleJson_obj = stageOper.moudleObj[moduleJsonObjId];
            stageOper.addModuleToStage(moduleJson_obj,modulePoint);
        });
        //左侧面板组件拖拽结束后的监听 end -------------------------------------

        //场景移动事件  虽然这里打开，但是我们不会让画布可以拖动，因为场景有框选框选，系统无法判断是要框选，还是拖动画布
        stageOper.stage.on('dragmove', function () {
           // stageOper.setStageGrid($("#hbfzx").is(":checked"));//设置网格
        });
        //组件点击，拖拉选中事件
        stageOper.addModuleTransformEvent();
        //设置组件右键菜单
        stageOper.addModuleContextmenu();

        //给场景添加键盘事件（上下左右）
        stageOper.setStageKeyboardEvent();

        //顶部功能按钮添加tips
        $(".butTips").mouseover(function() {

            layer.tips($(this).attr("tipsMess"), this, {

                tips: [3, "#4794ec"],
                time: 1000,
            });

        });
        //添加tips
        $('.butTips_top').hover(function(){
            $('#byzttip').attr("class","bottom_byzttip");
            var title=$(this).attr('data-title');
            $('#byzttip em').text(title);
            var pos=$(this).offset().left;
            var top=$(this).offset().top+$(this).outerHeight()+8;
            var dis=($('#byzttip').outerWidth()-$(this).outerWidth())/2;
            var l=pos-dis;

            $('#byzttip').css({'left':l+'px'}).css({'top':top+'px'}).show();
        },function(){
            $('#byzttip').hide();
        });


        //按钮监听事件
        $("#left_shrink").click(function(){
            $(".main_page_center_left").slideToggle(100,function(){
                if($(this).is(":visible")){//可见
                    $("#left_shrink").attr("class","layui-icon layui-icon-left");
                }else{//不可见
                    $("#left_shrink").attr("class","layui-icon layui-icon-right");
                }
            });
        });
        $("#right_shrink").click(function(){
            $(".main_page_center_right").slideToggle(100,function(){
                if($(this).is(":visible")){//可见
                    $("#right_shrink").attr("class","layui-icon layui-icon-right");
                }else{//不可见
                    $("#right_shrink").attr("class","layui-icon layui-icon-left");
                }


            });
        });

        //刷新当前图纸函数
        function refreshStage(){
            stageOper.initStage(stage_id,element);
            //组件点击，拖拉选中事件
            stageOper.addModuleTransformEvent();
            //设置组件右键菜单
            stageOper.addModuleContextmenu();

            //给场景添加键盘事件（上下左右）
            stageOper.setStageKeyboardEvent();
        }

        $("#reNew").click(function(){
            refreshStage();
        })
        //背景图片选择事件
        $("#stageBackgroundImage").click(function(e){
           /* var divSwitchElem = $(this);
            var tdElem = divSwitchElem.closest("td");
            var trElem = tdElem.closest("tr");
            var tableView = trElem.closest(".layui-table-view");*/
            layer.open({
                title:'请选择背景图片',
                type: 2,
                area: ['800px', '550px'],
                skin: 'layer-class',
                fixed: false, //不固定
                maxmin: true,
                content: 'stageBackgroundImage.html?userId='+userId,
                end: function(index, layero){
                    if(imageBackgroundUrl!==''){
                        $("#stageBackgroundImage").attr('src',imageBackgroundUrl);
                        stageOper.setStageBackgroundImage(imageBackgroundUrl);
                    }

                }

            });
        });



        //预览
        $("#yl").click(function(){
            stageOper.stageMaxMin('restore');//放大缩小后要还原

            var iWidth =  (window.screen.width-10)/5*4;                        //弹出窗口的宽度;
            var iHeight = (window.screen.height-30)/5*4;                        //弹出窗口的高度;

            var iTop = (window.screen.height-30-iHeight)/2;       //获得窗口的垂直位置;
            var iLeft = (window.screen.width-10-iWidth)/2;        //获得窗口的水平位置;

            window.open("preview.html","newwindow",'height='+iHeight+',innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',toolbar=no,menubar=no,scrollbars=no,resizeable=no,location=no,status=no,copyhistory=no');
            //window.open("preview.html","_blank","height="+(window.screen.availHeight-300)+", width="+(window.screen.availWidth-300)+",toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes");
        });
        //保存
        $("#bc").click(function(){
            stageOper.stageMaxMin('restore');//放大缩小后要还原
            var stageBase64 = stageOper.getStageBase64();
            stageOper.dealImage(stageBase64,500,stageOper.callbackSaveStageAll);//压缩base64图片，压缩后会在回调方法调用保存
            //保存时关闭辅助线
            stageOper.setStageGrid(false);
            $("#hbfzx").prop('checked', false);
            $("#gridColorGroup").hide();
            $('#gridColor').val("");
            form.render();
            //保存时，重载画面，以同步组件属性,延时不可少
            setTimeout(function(){
               refreshStage();
            },600)

        });
        //保存到模板
        // $("#bcmb").click(function(){
        //     stageOper.stageMaxMin('restore');//放大缩小后要还原
        //     var stageBase64 = stageOper.getStageBase64();
        //     stageOper.dealImage(stageBase64,500,stageOper.callbackSaveStageModule);//压缩base64图片，压缩后会在回调方法调用保存
        // });



        //按钮监听事件 组件右键菜单 start

        $("#module_lock").click(function(){
            stageOper.lockModule(currentModule,true);
        });
        $("#module_unlock").click(function(){
            stageOper.lockModule(currentModule,false);
        });
        $("#module_up").click(function(){
            stageOper.changeModuleZindex("up");
        });
        $("#module_down").click(function(){
            stageOper.changeModuleZindex("down");
        });
        $("#module_top").click(function(){
            stageOper.changeModuleZindex("top");
        });
        $("#module_bottom").click(function(){
            stageOper.changeModuleZindex("bottom");
        });
        $("#module_delete").click(function(){
            stageOper.deleteModule(currentModule);
        });
        $("#anchor_delete").click(function(){
            stageOper.deleteModuleAnchor();
        });
        $("#left_align").click(function(){
            stageOper.moduleAlign("left_align");
        });
        $("#right_align").click(function(){
            stageOper.moduleAlign("right_align");
        });
        $("#up_align").click(function(){
            stageOper.moduleAlign("up_align");
        });
        $("#buttom_align").click(function(){
            stageOper.moduleAlign("buttom_align");
        });
        $("#center_horizontally").click(function(){
            stageOper.moduleAlign("center_horizontally");
        });
        $("#vertical_horizontally").click(function(){
            stageOper.moduleAlign("vertical_horizontally");
        });




        //按钮监听事件 组件右键菜单 end

        //监听windows的点击事件
        $(document).on("click",function(){
            menuNode.style.display = 'none';
        });


    });


    //快捷键
    $("#shortcut_key").click( function () {
        hidenOrshow();
    });
    $("#pc_Shortcut_down").click( function () {
        hidenOrshow();
    });






    //全屏/还原
    $("#full").click( function () {
        if(isFullscreen()){
            fullExit();
        }else{
            fullScreen();
        }

    });
    window.onresize = function() {
        if (!isFullscreen()) { // 监听 狂口变化，切换全屏图标
            $("#full").attr("class","layui-icon layui-icon-screen-full");
        }
    }


});
//左侧面板组件拖拽开始的方法调用
function dragImage(ev){
    //var moduleJsonStr = $(ev.target.id).parent().children(":first").val();
    ev.dataTransfer.setData('text',ev.target.id);
}
function getStageStr(){
    return stageOper.getStageJson();

}

// 左侧图纸点击切换，1月29日新加函数
function changeDraw(drawId) {
    // console.log('左侧点击切换', e);
    location.href = "/static/optionZT/index_edit.html?stageId=" + drawId + "&selectOneWhere=" + localStorage.getItem("optionId");
}

function changeTextColor (id,type) {
	if(type==0){
	   document.getElementById(id).style.color="deepskyblue";
	}else{
	   document.getElementById(id).style.color="#111";
	}
	//event.target.style.color="deepskyblue";
}


//退出全屏 start
function fullScreen() {
    $("#full").attr("class","layui-icon layui-icon-screen-restore");
    var element = document.documentElement; //若要全屏页面中div，var element= document.getElementById("divID");
    //IE 10及以下ActiveXObject
    if (window.ActiveXObject) {
        var WsShell = new ActiveXObject('WScript.Shell')
        WsShell.SendKeys('{F11}');
    }
    //HTML W3C 提议
    else if (element.requestFullScreen) {
        element.requestFullScreen();
    }
    //IE11
    else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
    // Webkit (works in Safari5.1 and Chrome 15)
    else if (element.webkitRequestFullScreen) {
        element.webkitRequestFullScreen();
    }
    // Firefox (works in nightly)
    else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    }
}


function fullExit() {
    $("#full").attr("class","layui-icon layui-icon-screen-full");
    var element = document.documentElement; //若要全屏页面中div，var element= document.getElementById("divID");
    //IE ActiveXObject
    if (window.ActiveXObject) {
        var WsShell = new ActiveXObject('WScript.Shell')
        WsShell.SendKeys('{F11}');
    }
    //HTML5 W3C 提议
    else if (element.requestFullScreen) {
        document.exitFullscreen();
    }
    //IE 11
    else if (element.msRequestFullscreen) {
        document.msExitFullscreen();
    }
    // Webkit (works in Safari5.1 and Chrome 15)
    else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
    }
    // Firefox (works in nightly)
    else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
    }
}
// 判断是否全屏
function isFullscreen () {
    return document.fullscreenElement ||
        document.msFullscreenElement ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement || false;
}
//退出全屏 end

function hidenOrshow(){
    $("#pc_Shortcut").toggle(500);
}
//使用期限验证 暂时无用
function  deadlineForValidation(){
    $.ajax({
        url:"",
        type:"POST",
        cache: false,
        async:false,
        dataType:'json',
        beforeSend: function() {
            //请求前要处理的事情
        },
        success: function (data) {

        },
        error: function (e) {
           alert('请链接到互联网');
        }
    });
}

// -------------------------------------------------防止右键控制台--------

//window.oncontextmenu = function () { return false; }

// window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
//     var e = event || window.event || arguments.callee.caller.arguments[0];
//     if (e && e.keyCode == 123) {
//         layer.msg('控制台已禁止', {
//             offset: 't',
//             anim: 6,
//             icon:2
//         });
//         e.returnValue = false;
//         return (false);
//     }

// }
var ConsoleManager = {
    openCallback: function(){
        console.log('控制台打开了');
        try {
            window.open("about:blank", "_self")
        } catch(e) {
            var btn = document.createElement("button");
            btn.onclick = function() {
                window.open("about:blank", "_self")
            }
            btn.click()
        }
    },
    observer: function(){
        var obj = Object.create(null), t = Date.now(), that = this;
        Object.defineProperty(obj, "a", {
            get: function() {
                if(Date.now() - t > 100){
                    that.openCallback()
                }
            }
        });
        setInterval(function(){
            t = Date.now();
            (function(){})["constructor"]("debugger")();//debugger;
            console.log(obj.a);
        }, 200);
    },
    observerF: function(){
        var obj = Object.create(null), t = Date.now(), that = this;
        Object.defineProperty(obj, "a", {
            get: function() {
                if(Date.now() - t > 100){
                    that.openCallback()
                }
            }
        });
        setInterval(function(){
            t = Date.now();
            (function(){})["constructor"]("debugger")();//debugger;
            console.log(obj.a);
        }, 200);
    },
    init: function(){
        var t = window.navigator.userAgent.toLowerCase();
        t.indexOf("firefox") >= 0 ? this.observerF() : this.observer();
    }
}
//ConsoleManager.init();

